import NavBar from "../components/NavBar";
import BackButton from "../components/BackButton";
import SwitchCtrl from "../components/SwitchCtrl";

export const navbarMixin = {
    components: {
        NavBar,
        BackButton
    }
}

export const switchctrlMixin = {
    components: {
        SwitchCtrl
    }
}

export const methodsMixin = {
    methods:{
        transform(val) {
            if (!val) {
                return '';
            }

            if (val.length === 2) {
                return val.split('').map((v, i) => {
                    if (i === 0) {
                        v = `<span style="margin-right: 1em;">${v}</span>`;
                    }
                    return v;
                }).join('');
            }


            let a = val.split('\r\n'), str = '';

            if (a.length > 1) {
                a.forEach(item => {
                    if (item !== '') {
                        str += `<span style="display: block;">${item}</span>`;
                    }
                });
            }

            (str === '') && ( str = val);

            return str;
        }
    }
}

export const filtersMixin = {
    filters: {
        // 性别
        sex(sex) {
            return sex === '女' ? '女' : '男';
        },
        // 出生日期格式化
        dateFormat(date) {

            if (!date) {
                return '';
            }

            if (date.length < 6) {
                return date;
            }

            if (date.indexOf('.') !== -1) {
                return date;
            }

            let dateString = date.substring(0, 6);
            dateString = dateString.slice(0, 4) + '.' + dateString.slice(4);

            return dateString;
        },
        // 根据出生日期计算年龄
        age(age) {
            if (!age) {
                return '';
            }
            let returnAge;
            let birthYear = age.substring(0, 4),
                birthMonth = age.substring(4, 6);

            let d = new Date();
            var nowYear = d.getFullYear();
            var nowMonth = d.getMonth() + 1;

            if (nowYear === birthYear) {
                returnAge = 0;  //同年 则为0岁
            } else {
                var ageDiff = nowYear - birthYear; //年之差
                if (ageDiff > 0) {
                    var monthDiff = nowMonth - birthMonth;//月之差
                    if (monthDiff < 0) {
                        returnAge = ageDiff - 1;
                    } else {
                        returnAge = ageDiff;
                    }
                } else {
                    returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
                }
            }

            return returnAge;//返回周岁年龄
        }
    }
}
